package com.spring.security.controller;

import com.spring.security.model.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * @author HouKunLin
 */
@Slf4j
@RestController
@RequestMapping("/")
public class HomeController {

    @Secured("ROLE_ADMIN")
    @GetMapping("/user/principal1")
    public JsonResult principal(Principal principal) {
        return JsonResult.ok(principal).put("class", principal.getClass().getName());
    }

    @Secured("user:update")
    @GetMapping("/user/principal2")
    public JsonResult principal2(Authentication authentication) {
        JsonResult json = JsonResult.ok();
        json.data()
                .put("authorities", authentication.getAuthorities())
                .put("credentials", authentication.getCredentials())
                .put("details", authentication.getDetails())
                .put("principal", authentication.getPrincipal())
                .put("principal.class", authentication.getPrincipal().getClass().getName())
                .put("authenticated", authentication.isAuthenticated())
                .put("name", authentication.getName())
                .put("class", authentication.getClass().getName())
        ;
        return json;
    }

    @Secured("user:update")
    @GetMapping("/user/principal3")
    public JsonResult principal3(Authentication authentication) {
        return JsonResult.ok(authentication).put("class", authentication.getClass().getName());
    }

    @Secured("user:update")
    @GetMapping("/user/principal4")
    public JsonResult principal4(UsernamePasswordAuthenticationToken authentication) {
        return JsonResult.ok(authentication).put("class", authentication.getClass().getName());
    }

    @GetMapping("/user/principal5")
    public JsonResult principal5() {
        Authentication principal = SecurityContextHolder.getContext().getAuthentication();
        log.debug("principal : {}", principal);
        return JsonResult.ok(principal).put("class", principal.getClass().getName());
    }

}
